using System;
using ECommerce.Web.DesignByContract;
using ECommerce.Web.Models;
using ECommerce.Web.NHibernate.Sessions;
using ECommerce.Web.Services.ShoppingSessions;
using NHibernate;

namespace ECommerce.Web.Commands
{
    public interface IAddProductToBasketCommand
    {
        void Handle(AddProductToBasketMessage message);
    }

    public class AddProductToBasketMessage
    {
        public int ProductId { get; set; }
        public int Quantity { get; set; }
    }

    public class AddProductToBasketCommand : IAddProductToBasketCommand
    {
        private readonly IShoppingSession shoppingSession;

        public AddProductToBasketCommand(IShoppingSession shoppingSession)
        {
            this.shoppingSession = shoppingSession;
        }

        public void Handle(AddProductToBasketMessage message)
        {
            Contract.Require(message.ProductId != default(int), "ProductId should not be default value.");

            Guid shopperToken = this.shoppingSession.GetShopperToken();

            ISession session = SessionSource.Current.GetSession();

            var shopper = session.FindById<IShopperWithBasket>(shopperToken);
            
            using (ITransaction transaction = session.BeginTransaction())
            {
                shopper.AddProductToBasket(new Product() { Id = message.ProductId }, message.Quantity);

                transaction.Commit();
            }
        }
    }
}